// 用户隐私设置状态管理
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { userPrivacyService } from '@/services'
import type { 
  UserPrivacySetting,
  UpdatePrivacySettingRequest
} from '@/types'

export const useUserPrivacyStore = defineStore('userPrivacy', () => {
  // 状态
  const privacySetting = ref<UserPrivacySetting | null>(null)
  const isLoading = ref(false)
  const error = ref<string | null>(null)
  
  // 计算属性
  const isStrictMode = computed(() => {
    if (!privacySetting.value) return false
    
    const setting = privacySetting.value
    return (
      setting.friendRequestPermission === 'NOBODY' ||
      (!setting.allowSearchByPhone && !setting.allowSearchByEmail && !setting.allowSearchByUsername) ||
      (!setting.showOnlineStatus && !setting.allowGroupInvite)
    )
  })
  
  const privacyLevel = computed(() => {
    if (!privacySetting.value) return 'unknown'
    
    const setting = privacySetting.value
    
    // 开放模式
    if (
      setting.friendRequestPermission === 'EVERYONE' &&
      setting.allowSearchByPhone &&
      setting.allowSearchByEmail &&
      setting.allowSearchByUsername &&
      setting.showOnlineStatus &&
      setting.allowGroupInvite
    ) {
      return 'open'
    }
    
    // 严格模式
    if (
      setting.friendRequestPermission === 'CONTACTS_ONLY' ||
      setting.friendRequestPermission === 'NOBODY'
    ) {
      return 'strict'
    }
    
    // 平衡模式
    return 'balanced'
  })
  
  const searchRestrictions = computed(() => {
    if (!privacySetting.value) return []
    
    const restrictions = []
    const setting = privacySetting.value
    
    if (!setting.allowSearchByPhone) restrictions.push('手机号')
    if (!setting.allowSearchByEmail) restrictions.push('邮箱')
    if (!setting.allowSearchByUsername) restrictions.push('用户名')
    
    return restrictions
  })
  
  const visibilitySettings = computed(() => {
    if (!privacySetting.value) return []
    
    const settings = []
    const setting = privacySetting.value
    
    if (!setting.showOnlineStatus) settings.push('隐藏在线状态')
    if (!setting.allowGroupInvite) settings.push('禁止群组邀请')
    if (setting.requireVerification) settings.push('需要验证消息')
    
    return settings
  })
  
  const friendRequestLevelText = computed(() => {
    if (!privacySetting.value) return '未知'
    
    switch (privacySetting.value.friendRequestPermission) {
      case 'EVERYONE':
        return '所有人'
      case 'FRIENDS_OF_FRIENDS':
        return '朋友的朋友'
      case 'CONTACTS_ONLY':
        return '仅联系人'
      case 'NOBODY':
        return '不允许'
      default:
        return '未知'
    }
  })
  
  // 操作方法
  
  /**
   * 加载用户隐私设置
   */
  async function loadPrivacySetting(userId: number, refresh = false): Promise<void> {
    try {
      if (refresh || !privacySetting.value) {
        isLoading.value = true
        error.value = null
      }
      
      const setting = await userPrivacyService.getUserPrivacySetting(userId)
      privacySetting.value = setting
    } catch (err) {
      error.value = err instanceof Error ? err.message : '加载隐私设置失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }
  
  /**
   * 更新隐私设置
   */
  async function updatePrivacySetting(userId: number, request: UpdatePrivacySettingRequest): Promise<void> {
    try {
      isLoading.value = true
      error.value = null
      
      const updatedSetting = await userPrivacyService.updatePrivacySetting(userId, request)
      privacySetting.value = updatedSetting
    } catch (err) {
      error.value = err instanceof Error ? err.message : '更新隐私设置失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }
  
  /**
   * 重置为默认设置
   */
  async function resetToDefault(userId: number): Promise<void> {
    try {
      isLoading.value = true
      error.value = null
      
      const defaultSetting = await userPrivacyService.resetToDefault(userId)
      privacySetting.value = defaultSetting
    } catch (err) {
      error.value = err instanceof Error ? err.message : '重置隐私设置失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }
  
  /**
   * 应用推荐的隐私设置
   */
  async function applyRecommendedSettings(userId: number, level: 'open' | 'balanced' | 'strict'): Promise<void> {
    try {
      isLoading.value = true
      error.value = null
      
      const updatedSetting = await userPrivacyService.applyRecommendedSettings(userId, level)
      privacySetting.value = updatedSetting
    } catch (err) {
      error.value = err instanceof Error ? err.message : '应用推荐设置失败'
      throw err
    } finally {
      isLoading.value = false
    }
  }
  
  /**
   * 检查用户是否允许被搜索
   */
  async function canBeSearched(userId: number, searchType: string, searchValue: string): Promise<boolean> {
    try {
      return await userPrivacyService.canBeSearched(userId, searchType, searchValue)
    } catch (err) {
      console.error('检查搜索权限失败:', err)
      return false
    }
  }
  
  /**
   * 检查用户是否允许接收好友请求
   */
  async function canReceiveFriendRequest(fromUserId: number, toUserId: number): Promise<boolean> {
    try {
      return await userPrivacyService.canReceiveFriendRequest(fromUserId, toUserId)
    } catch (err) {
      console.error('检查好友请求权限失败:', err)
      return false
    }
  }
  
  /**
   * 更新单个隐私设置项
   */
  async function updateSingleSetting(
    userId: number, 
    key: keyof UpdatePrivacySettingRequest, 
    value: any
  ): Promise<void> {
    const request: UpdatePrivacySettingRequest = { [key]: value }
    await updatePrivacySetting(userId, request)
  }
  
  /**
   * 切换好友请求权限
   */
  async function toggleFriendRequestPermission(userId: number): Promise<void> {
    if (!privacySetting.value) return
    
    const currentPermission = privacySetting.value.friendRequestPermission
    let nextPermission: typeof currentPermission
    
    switch (currentPermission) {
      case 'EVERYONE':
        nextPermission = 'FRIENDS_OF_FRIENDS'
        break
      case 'FRIENDS_OF_FRIENDS':
        nextPermission = 'CONTACTS_ONLY'
        break
      case 'CONTACTS_ONLY':
        nextPermission = 'NOBODY'
        break
      case 'NOBODY':
        nextPermission = 'EVERYONE'
        break
      default:
        nextPermission = 'EVERYONE'
    }
    
    await updateSingleSetting(userId, 'friendRequestPermission', nextPermission)
  }
  
  /**
   * 切换搜索权限
   */
  async function toggleSearchPermission(
    userId: number, 
    type: 'phone' | 'email' | 'username'
  ): Promise<void> {
    if (!privacySetting.value) return
    
    const currentValue = type === 'phone' 
      ? privacySetting.value.allowSearchByPhone
      : type === 'email'
      ? privacySetting.value.allowSearchByEmail
      : privacySetting.value.allowSearchByUsername
    
    const key = type === 'phone' 
      ? 'allowSearchByPhone'
      : type === 'email'
      ? 'allowSearchByEmail'
      : 'allowSearchByUsername'
    
    await updateSingleSetting(userId, key, !currentValue)
  }
  
  /**
   * 切换在线状态显示
   */
  async function toggleOnlineStatus(userId: number): Promise<void> {
    if (!privacySetting.value) return
    
    await updateSingleSetting(userId, 'showOnlineStatus', !privacySetting.value.showOnlineStatus)
  }
  
  /**
   * 切换群组邀请权限
   */
  async function toggleGroupInvite(userId: number): Promise<void> {
    if (!privacySetting.value) return
    
    await updateSingleSetting(userId, 'allowGroupInvite', !privacySetting.value.allowGroupInvite)
  }
  
  /**
   * 切换验证消息要求
   */
  async function toggleRequireVerification(userId: number): Promise<void> {
    if (!privacySetting.value) return
    
    await updateSingleSetting(userId, 'requireVerification', !privacySetting.value.requireVerification)
  }
  
  /**
   * 获取隐私设置摘要
   */
  const privacySummary = computed(() => ({
    level: privacyLevel.value,
    friendRequestLevel: friendRequestLevelText.value,
    searchRestrictions: searchRestrictions.value,
    visibilitySettings: visibilitySettings.value,
    isStrictMode: isStrictMode.value
  }))
  
  /**
   * 清除错误状态
   */
  function clearError(): void {
    error.value = null
  }
  
  /**
   * 重置状态
   */
  function reset(): void {
    privacySetting.value = null
    isLoading.value = false
    error.value = null
  }
  
  return {
    // 状态
    privacySetting,
    isLoading,
    error,
    
    // 计算属性
    isStrictMode,
    privacyLevel,
    searchRestrictions,
    visibilitySettings,
    friendRequestLevelText,
    privacySummary,
    
    // 方法
    loadPrivacySetting,
    updatePrivacySetting,
    resetToDefault,
    applyRecommendedSettings,
    canBeSearched,
    canReceiveFriendRequest,
    updateSingleSetting,
    toggleFriendRequestPermission,
    toggleSearchPermission,
    toggleOnlineStatus,
    toggleGroupInvite,
    toggleRequireVerification,
    clearError,
    reset
  }
})